package com.example.util;

import java.sql.*;

public class DBUtil {

    static Connection conn;
    static String url = "jdbc:mysql://localhost:3306/shop";
    static String user = "root";
    static String password = "123456";

    static {
        //1.连接数据库
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 连接到数据库的方法
    public static Connection getConnection() {
        try {
            conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    // 关闭与数据库的连接方法
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        conn = DBUtil.getConnection();
        if (conn == null)
            System.out.println("数据库连接失败");
        else
            System.out.println("连接成功");
    }
}
